package com.mvc.servlet;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.action.Action;
import com.mvc.action.ActionForm;
import com.mvc.entity.StrutsBean;

public class StrutsServlet extends HttpServlet{

	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		
		String path = req.getServletPath();
		
		path = path.split("\\.")[0];
		
		Map<String, StrutsBean> map = (Map<String, StrutsBean>) getServletContext().getAttribute("struts-config");
		StrutsBean bean = map.get(path);
		
		ActionForm actionForm = getBean(bean.getEntityClass(), req);
		
		try {
			Class clazz = Class.forName(bean.getActionClass());
			Action action = (Action)clazz.newInstance();
			String url = action.execute(actionForm);
			String value = bean.getForwards().get(url);
			RequestDispatcher rd = req.getRequestDispatcher(value);
			rd.forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
				
		
	}

	private ActionForm getBean(String entityClass, HttpServletRequest req) {
		
		ActionForm actionForm = null;
		
		try {
			Class clazz = Class.forName(entityClass);
			actionForm = (ActionForm) clazz.newInstance();
			
			Field[] fields = clazz.getDeclaredFields();
			for(Field field : fields) {
				field.setAccessible(true);
				field.set(actionForm, req.getParameter(field.getName()));
				field.setAccessible(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return actionForm;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
